<template>
  <a-modal
    :open="visibleModal"
    title="编辑授权"
    width="416px"
    :confirm-loading="confirmLoading"
    centered
    class="edit-modal-12"
    @cancel="handleCancel"
    @ok="onSubmit"
  >
    <div class="modal-wrap h-309">
      <div :title="`${detailInfo?.onlineId}_${detailInfo?.algoName}_${detailInfo?.version}`" class="title elliptical-1">
        {{ detailInfo?.onlineId }}_{{ detailInfo?.algoName }}_{{ detailInfo?.version }}
      </div>
      <a-spin :spinning="loading" tip="数据加载中">
        <a-form ref="formRef" :model="formState" layout="vertical" :colon="false" name="basic" class="form my-scrollbar" :rules="rules">
          <a-form-item :label="`新增调用量（${detailInfo?.totalCallNum}）`" name="addTotalCallNum" class="form-item">
            <a-input-number
              v-model:value.trim="formState.addTotalCallNum"
              style="width: 100%"
              :min="0"
              :max="99999999"
              placeholder="请输入新增调用量"
              :precision="0"
              :formatter="transformNum"
              :parser="transformNum"
              @keydown.stop=""
            />
          </a-form-item>
          <a-form-item :label="`新增QPS（${detailInfo?.qps}）`" name="addQps" class="form-item">
            <a-input-number
              v-model:value.trim="formState.addQps"
              style="width: 100%"
              :min="0"
              :max="detailInfo?.availableQps"
              :placeholder="`可申请额度：${detailInfo?.availableQps}`"
              :precision="0"
              :formatter="transformNum"
              :parser="transformNum"
              @keydown.stop=""
            />
          </a-form-item>
          <a-form-item label="有效期" name="time" class="form-item required">
            <a-range-picker v-model:value="formState.time" show-time @change="handleChange" />
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { FormInstance, message } from 'ant-design-vue'
  import { Rule } from 'ant-design-vue/lib/form'
  import dayjs from 'dayjs'
  import { dateFormat, debounce } from 'g6-fn'
  import { ref } from 'vue'

  import { authApi } from '@/services/api'

  import { AuthApiDetail } from '../../types/online-service'

  interface FormState {
    addTotalCallNum: number | undefined
    addQps: number | undefined
    time: any
  }

  const emits = defineEmits(['on-success'])

  const visibleModal = ref(false)
  const loading = ref<boolean>(false)
  const detailId = ref<string>('')

  const formRef = ref<FormInstance>()
  const formState = ref<FormState>({
    addTotalCallNum: undefined,
    addQps: undefined,
    time: []
  })
  const rules: Record<string, Rule[]> = {
    time: [{ required: true, message: '请选择有效期', trigger: 'change' }]
  }

  const confirmLoading = ref(false)
  const onSubmit = debounce(async () => {
    confirmLoading.value = true
    try {
      await formRef.value?.validate()
      const params = {
        id: detailId.value,
        ...formState.value,
        time: undefined,
        updateBeforeValidTime: dateFormat(formState.value.time[0] as string, 'YYYY-MM-DD HH:mm:ss'),
        updateAfterValidTime: dateFormat(formState.value.time[1] as string, 'YYYY-MM-DD HH:mm:ss')
      }
      await authApi.updateOnlineAudit(params)
      message.success('操作成功')
      emits('on-success')
      handleCancel()
      confirmLoading.value = false
    } catch (error) {
      console.log(error)
      confirmLoading.value = false
    }
  }, 500)

  const detailInfo = ref<AuthApiDetail>()
  const getOnlineUpdateById = async (id: string) => {
    console.log('getOnlineUpdateById')

    try {
      loading.value = true
      const { data } = await authApi.getOnlineUpdateById(id)()
      detailInfo.value = data as AuthApiDetail
      Object.assign(formState.value, {
        time: [dayjs(data.beforeValidTime), dayjs(data.afterValidTime)]
      })
      loading.value = false
      visibleModal.value = true
    } catch (error) {
      loading.value = false
    }
  }

  const openModal = (id: string) => {
    detailId.value = id
    getOnlineUpdateById(id)
  }

  const handleCancel = () => {
    detailId.value = ''
    formState.value = {
      addTotalCallNum: undefined,
      addQps: undefined,
      time: []
    }
    visibleModal.value = false
  }
  const transformNum = (value: number | string): any => {
    let v = null
    switch (typeof value) {
      case 'string':
        v = isNaN(+value) ? 0 : value.replace(/\./g, '')
        break
      case 'number':
        v = isNaN(value) ? 0 : String(value).replace(/\./g, '')
        break
      default:
        v = 0
    }
    return v
  }
  const handleChange = (val: any) => {
    const [startTime, endTime] = val
    const isStartAfterEnd =
      dayjs(startTime, 'YYYY-MM-DD HH:mm:ss').isAfter(endTime) || dayjs(startTime, 'YYYY-MM-DD HH:mm:ss').isSame(endTime)
    console.log(isStartAfterEnd, 'isStartAfterEnd')

    if (isStartAfterEnd) {
      console.log('hello')
      formState.value.time = []
    }
  }

  defineExpose({
    openModal,
    handleCancel
  })
</script>

<style lang="less" scoped>
  @import '../../styles/common.less';
</style>
